<script setup name="NewComp">
import { reactive, ref } from 'vue'
import { genFileId } from 'element-plus'
import { onMounted } from 'vue'
const formState = reactive({
  workTime: '',
  offWorkTime: '',
  salary: 0,
  salaryDate: 1,
  holidayMode: 2, //0大小周 1单休  2双休
  themeColor: '#ffa500',
  picture: []
})

onMounted(async () => {
  try {
    const config = await window.electronAPI.loadConfig()
    delete config.default
    delete config.picture
    Object.assign(formState, config)
  } catch (error) {
    // 本地配置信息读取失败
    console.log('本地配置信息读取失败')
  }
})

const options = [
  {
    value: 0,
    label: '大小周'
  },
  {
    value: 1,
    label: '单休'
  },
  {
    value: 2,
    label: '双休'
  }
]

const formatCurrency = (value) => {
  if (value === null || value === undefined || value === '') return '￥ '
  const [integer, decimal] = String(value).split('.')
  const formattedInt = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
  return decimal ? `￥ ${formattedInt}.${decimal}` : `￥ ${formattedInt}`
}

const parseCurrency = (value) => {
  // 移除非数字和点，禁止负号和字母
  const cleaned = value.replace(/[^0-9.]/g, '')

  // 只保留一个小数点
  const parts = cleaned.split('.')
  if (parts.length > 2) {
    return parts[0] + '.' + parts[1]
  }

  // 限制最多两位小数（可选）
  if (parts[1]) {
    parts[1] = parts[1].slice(0, 2)
  }

  return parts.join('.')
}

const fileType = ['jpeg', 'png', 'jpg']
const fileSize = 2 //单位为mb

const upload = ref()

const fileReset = () => {
  formState.picture = []
  upload.value.clearFiles()
}

const handleExceed = (files, fileList) => {
  upload.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value.handleStart(file)
}

const handleFileChange = (file) => {
  // if(!file || formState.picture.length <= 0) return
  // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用,删除文件不会调用
  // 校检文件类型
  let fileExtension = ''
  if (file.name.lastIndexOf('.') > -1) {
    fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
  }
  const isTypeOk = fileType.some((type) => {
    if (fileExtension && fileExtension.indexOf(type) > -1) return true
    return false
  })
  if (!isTypeOk) {
    console.log('文件类型不符合要求')
    fileReset()
    return false
  }
  // 校检文件大小
  const isLt = file.size / 1024 / 1024 < fileSize
  if (!isLt) {
    console.log('文件过大')
    fileReset()
    return false
  }

  formState.picture = [file]
}

const form = ref()
const onCancel = () => {
  fileReset()
  window.electronAPI.shutdownSetting('setting-close')
}

const onSubmit = async () => {
  const data = { ...formState }
  try {
    if (formState.picture.length > 0) {
      const res = await getBase64(formState.picture[0].raw)
      data.picture = res
    }else{
      delete data.picture
    }
    if(formState.themeColor) {
      const el = document.documentElement;
      el.style.setProperty("--el-color-primary", formState.themeColor);
    }
    onCancel()
  } catch (error) {
    throw new Error('文件转换错误，无法转换为base64格式')
  }
  window.electronAPI.saveConfig(JSON.stringify(data))

  function getBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = (e) => resolve(e.target.result)
      reader.onerror = (error) => reject(error)
    })
  }
}

const onReset = () => {
  onCancel()
  window.electronAPI.resetConfig()
}
</script>

<template>
  <div class="setting-form">
    <div class="container">
      <el-form ref="form" :model="formState" label-width="74px">
        <div class="form-item-border">
          <el-form-item label="上班时间" prop="workTime">
            <el-time-select v-model="formState.workTime" style="width: 100%" :max-time="formState.offWorkTime" placeholder="00:00:00" start="06:00" step="00:30" end="21:00" />
          </el-form-item>
          <el-form-item label="下班时间" prop="offWorkTime">
            <el-time-select v-model="formState.offWorkTime" style="width: 100%" :min-time="formState.workTime" placeholder="00:00:00" start="06:00" step="00:30" end="21:00" />
          </el-form-item>
          <el-form-item label="假期模式" prop="holidayMode">
            <el-select v-model="formState.holidayMode">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </div>
        <div style="margin: 10px 0" class="form-item-border">
          <el-form-item label="月薪" prop="salary">
            <el-input v-model="formState.salary" :formatter="formatCurrency" :parser="parseCurrency"></el-input>
          </el-form-item>
          <el-form-item label="发薪日" prop="salaryDate">
            <el-input-number v-model="formState.salaryDate" :min="1" :max="31" style="width: 100%" />
          </el-form-item>
        </div>
        <div class="form-item-border">
          <el-form-item label="主题色" prop="themeColor">
            <el-color-picker v-model="formState.themeColor" :show-alpha="true" />
          </el-form-item>
          <el-form-item label="插图" prop="picture">
            <div style="height: 42px">
              <el-upload ref="upload" action="#" :auto-upload="false" :limit="1" :on-exceed="handleExceed" :on-change="handleFileChange">
                <el-button type="primary" plain size="small">选择附件</el-button>
              </el-upload>
            </div>
          </el-form-item>
          <el-form-item>
            <div style="margin-top: 20px; width: 100%; display: flex; justify-content: space-between">
              <div class="left">
                <el-button @click="onReset">还 原</el-button>
              </div>
              <div class="right">
                <el-button @click="onSubmit">确 定</el-button>
                <el-button @click="onCancel">取 消</el-button>
              </div>
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
$gap: 6px;

.setting-form {
  background-color: #d9d9d9;
  padding: $gap;
  .container {
    border-radius: 5px;
    background-color: #d9d9d9;
  }

  .custom-input-size {
    width: 100%;
  }

  .form-item-border {
    border: 1px solid #d9d9d9;
    background-color: #fff;
    border-radius: 4px;
    padding: 16px;
  }
}
</style>
